package com.example.search.config;

import co.elastic.clients.elasticsearch.ElasticsearchAsyncClient;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import lombok.Getter;
import lombok.Setter;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Getter
@Setter
@Configuration
@ConfigurationProperties(prefix = "elasticsearch")
public class ElasticSearchConfig {
    private String host = "192.168.1.5";
    private int port = 9200;
//旧版本RestHighLevelClient
//    @Bean
//    public RestClientTransport client(){
//        return new RestClientTransport(
//                RestClient.builder( new HttpHost( host, port, "http" )).build(),
//                new JacksonJsonpMapper()
//        );
//    }

    //新版本Java API Client
    //新版版还支持创建安全连接，使用SSLContext
    @Bean
    public ElasticsearchClient elasticsearchClient(){
        //创建低级客户端，负责所有传输级问题：连接池、重试、节点发现等
        RestClient restClient = RestClient.builder(
                new HttpHost(host,port)).build();
        //使用Jackson映射器创建传输层，方便ES与应用程序类集成
        ElasticsearchTransport transport = new RestClientTransport(
                restClient,new JacksonJsonpMapper());
        //创建API 客户端
        //阻塞
        return new ElasticsearchClient(transport);
        //异步非阻塞
//        return new ElasticsearchAsyncClient(transport);
    }

}
